package com.petmall.service;

import com.petmall.entity.*;
import com.petmall.mapper.CartMapper;
import com.petmall.mapper.ItemMapper;
import com.petmall.mapper.OrderMapper;
import com.petmall.util.ItemUtil;
import com.petmall.util.OrderUtil;
import com.petmall.util.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by pig2guang on 2017/4/20.
 */
@Service
public class OrderService {

    @Autowired
    private OrderMapper ordermapper;

    @Autowired
    private CartMapper cartmapper;

    @Autowired
    private ItemMapper itemmapper;

    @Autowired
    private UserService userservice;

    @Autowired
    private MessageService messageservice;

    //通过订单号获取订单详情
    public Order getOrderByOrderId(String order_id){
        return ordermapper.selectOrderByOrderId(order_id);
    }

    //创建新的订单,返回订单号
    public String creatOrder(Order order, Object user){
        long user_id = new UserUtil().getUserId(user);
        List<Cart> cart_items = getItemsFromCart(user_id); //从购物车中获取该订单所要包含的商品
        String order_id = getOrderId(); //生成订单号
        int status = new OrderUtil().status_unpaid; //订单状态置为未支付状态
        double item_total_price = getItemsTotalPrice(user_id, cart_items); //获取订单所有商品总价
        double post_fee = new OrderUtil().post_fee; //获取邮费
        ordermapper.insertOrder(order_id, getCreatTime(), status, item_total_price, post_fee, order.getReceiver_name(), order.getReceiver_phone(), order.getReceiver_address(), user_id); //数据库操作插入该新订单
        addItemsToOrder(order_id, user_id, cart_items); //关联该订单所包含的商品
        cartmapper.deleteAllItemsByUserId(user_id); //订单生成后清空购物车内的商品
        return order_id;
    }

    //获取用户所有未支付的订单
    public ArrayList<Order_items> getUnpaidUserOrders(Object user){
       return getUserOrders(user, new OrderUtil().status_unpaid);
    }

    //获取用户所有待发货的订单
    public ArrayList<Order_items> getUnSentUserOrders(Object user){
        return getUserOrders(user, new OrderUtil().status_unsent);
    }

    //获取用户所有待收货的订单
    public ArrayList<Order_items> getUnreceivedUserOrders(Object user){
        return getUserOrders(user, new OrderUtil().status_unreceived);
    }

    //获取用户所有待评价的订单
    public ArrayList<Order_items> getUnreviewedUserOrders(Object user){
        return getUserOrders(user, new OrderUtil().status_unreviewed);
    }

    //获取用户所有已完成的订单
    public ArrayList<Order_items> getCompletedUserOrders(Object user){
        return getUserOrders(user, new OrderUtil().status_completed);
    }

    //获取所有订单
    public List<Order> getAllOrders(){
        return ordermapper.selectAllOrder();
    }

    //将未支付订单的状态改为已支付待发货状态
    public void updateUnpaidOrderToUnsent(String order_id){
        updateOrderStatus(order_id, new OrderUtil().status_unsent);
    }

    //将待发货订单的状态改为已发货待收货状态
    public void updateUnsentOrderToUnreceived(String order_id){
        updateOrderStatus(order_id, new OrderUtil().status_unreceived);
    }

    //将待收货订单的状态改为已收货待评价状态
    public void updateUnreceivedOrderToUnreviewed(String order_id, Object user){
        updateOrderStatus(order_id, new OrderUtil().status_unreviewed);//改状态
        for(Order_item item : getItemsByOrderId(order_id)){ //确认收货后将商品已售数量增加
            itemmapper.updateItemSales(item.getItem_id(), item.getNum());
        }
        Order order = getOrderByOrderId(order_id);
        int user_level_add = order.getItem_total_price().intValue(); //将价格折算成积分
        int user_gold_add = new Double(order.getItem_total_price() * new UserUtil().gold_rate).intValue(); //将价格折算成金币数量
        Long user_id = new UserUtil().getUserId(user);
        String time= getCreatTime();
        userservice.updateUserLevelAndGold(user_id, user_level_add, user_gold_add);//增加用户积分和金豆
        //userservice.addUserLevelDetail(user_id, user_level_add, "订单:"+order_id+"已确认收货", time);
        //userservice.addUserGoldDetail(user_id, user_gold_add, "订单:"+order_id+"已确认收货", time);
    }

    //将待评价订单的状态改为已完成状态
    public void updateUnreviewedOrderToCompleted(String order_id){
        updateOrderStatus(order_id, new OrderUtil().status_completed);
    }

    //将订单的状态改为已取消状态
    public void updateOrderStatusToCancled(String order_id){
        updateOrderStatus(order_id, new OrderUtil().status_cancled);
        for(Order_item item : getItemsByOrderId(order_id)){ //取消订单后将商品库存数量增加
            itemmapper.updateItemNum(item.getItem_id(), item.getNum());
        }
    }

    //评价
    public String reviewOrderItem(String score, String detail, String order_item_id,String item_id, Object user){
        itemmapper.insertReview(new UserUtil().getUserId(user), Long.valueOf(order_item_id), Long.valueOf(item_id), new ItemUtil().item_review_status_normal, Integer.valueOf(score), detail ,getCreatTime());
        String order_id = ordermapper.selectOrderItemById(Long.valueOf(order_item_id)).getOrder_id();
        if(isAllReviewd(order_id) == true){
            updateUnreviewedOrderToCompleted(order_id);
            messageservice.addCompleteMessage(order_id, user);
        }
        return order_id;
    }

    //判断订单中是否还有未评价的商品
    public Boolean isAllReviewd(String order_id){
        Boolean isAllReviewed = true;
        for(Order_item_info item : getOrderItemsInfo(order_id)){
            if(itemmapper.selectItemReviewByOrderItemId(item.id) == null){
                isAllReviewed = false;
            }
        }
        return isAllReviewed;
    }

    //列举出该订单下待评价的商品
    public List<Order_item_review> listOrderItemToReview(String order_id){
        ArrayList<Order_item_review> order_items_review = new ArrayList<Order_item_review>();
        for(Order_item_info item : getOrderItemsInfo(order_id)){
            Order_item_review order_item_review = new Order_item_review(item, itemmapper.selectItemReviewByOrderItemId(item.id));
            order_items_review.add(order_item_review);
        }
        return order_items_review;
    }

    //管理员发货
    public void sendOrder(Order order){
        updateLogisticsInfo(order.getOrder_id(), order.getShipping_name(), order.getShipping_code());
        updateUnsentOrderToUnreceived(order.getOrder_id());
        messageservice.addSendMessage(order.getOrder_id(), order.getUser_id());
    }

    //更新订单物流信息
    public void updateLogisticsInfo(String order_id, String shipping_name, String shipping_code){
        ordermapper.updateOrderLogisticsInfo(order_id, shipping_name, shipping_code);
    }

    //获取订单下所有商品的详细信息
    public List<Order_item_info> getOrderItemsInfo(String order_id){
        ArrayList<Order_item_info> order_items_info = new ArrayList<Order_item_info>();
        for(Order_item order_item : getItemsByOrderId(order_id)){
            Item item = getItemInfoByItemId(order_item.getItem_id());
            Order_item_info order_item_info = new Order_item_info(order_item.getId(),order_item.getNum(),order_item.getItem_id(),item.getName(),item.getPrice(),order_item.getNum()*item.getPrice(),item.getImage());
            order_items_info.add(order_item_info);
        }
        return order_items_info;
    }

    //改变订单状态
    private void updateOrderStatus(String order_id, int status){
        ordermapper.updateOrderStatus(order_id, status);
    }

    //获取该用户特定状态下的订单及所有关联商品详情
    private ArrayList<Order_items> getUserOrders(Object user, int status) {
        ArrayList<Order_items> orders = new ArrayList<Order_items>();
        for(Order order : getOrdersByStatus(status, new UserUtil().getUserId(user) )){
            ArrayList<Order_item_info> order_items_info = new ArrayList<Order_item_info>();
            //System.out.print("订单号:" + order.getOrder_id() + "总价：" + order.getItem_total_price() + "邮费：" + order.getPost_fee() + "邮寄：" + order.getReceiver_name() + order.getReceiver_phone() + order.getReceiver_address() + "\n" );
            for(Order_item order_item : getItemsByOrderId(order.getOrder_id())){
                Item item = getItemInfoByItemId(order_item.getItem_id());
                Order_item_info order_item_info = new Order_item_info(order_item.getId(),order_item.getNum(),order_item.getItem_id(),item.getName(),item.getPrice(),order_item.getNum()*item.getPrice(),item.getImage());
                //System.out.print(order_item.getItem_id() + ":" + order_item.getNum() + "\n");
                //System.out.print(item.getName() + item.getPrice() + item.getImage() + "\n");
                order_items_info.add(order_item_info);
            }
            Order_items order_items = new Order_items(order,order_items_info);
            orders.add(order_items);
        }
        return orders;
    }

    //生成订单号，方式为MC加上当前时间，例如‘MC20170101010101’
    private String getOrderId(){
        return  "MC" + getCreatTime() ;
    }

    //获取订单创建时间
    private String getCreatTime(){
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String time = format.format(date);
        return time ;
    }

    //获取购物车里所有商品的总价
    private double getItemsTotalPrice(long user_id, List<Cart> cart_items){
        double item_total_price = 0;
        for( Cart cart_item : cart_items ){
            item_total_price += itemmapper.selectItemById(cart_item.getItem_id()).getPrice() * cart_item.getNum();
        }
        return  item_total_price;
    }

    //将购物车里的商品逐一加入关联到指定的订单
    private void addItemsToOrder(String order_id, long user_id, List<Cart> cart_items){
        for( Cart cart_item : cart_items ){
            ordermapper.insertOrderItem(order_id, cart_item.getItem_id(), cart_item.getNum());
            itemmapper.updateItemNum(cart_item.getItem_id(), (0-cart_item.getNum()));
        }
    }

    //获取当前购物车里的所有商品
    private List<Cart> getItemsFromCart(long user_id){
        return cartmapper.selectCartByUserId(user_id);
    }

    //获取该用户所有该状态的订单
    private List<Order> getOrdersByStatus(int status, long user_id){
        return ordermapper.selectOrderByStatus(status, user_id);
    }

    //获取该订单下的所有关联的商品
    private List<Order_item> getItemsByOrderId(String order_id){
        return ordermapper.selectItemByOrderId(order_id);
    }

   //获取单个商品详情
    private Item getItemInfoByItemId(long item_id){
        return itemmapper.selectItemById(item_id);
    }

}
